package com.imau.controller;

import com.alibaba.fastjson.JSON;
import com.imau.common.entiry.ResultCode;
import com.imau.common.entiry.ResultEntity;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 方法反射: /student/add up
 * 方便后续业务处理的servlet能够处理多个请求方法
 * 获取请求路径：请求方法->反射调用请求方法
 * servlet：service方法
 * 其他servlet都是Baseconterllor this
 */
public class Baseconterllor extends HttpServlet {



    @SneakyThrows
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{


        //1. 获取请求的URI
        String requestURI = request.getRequestURI();

        //2. 截取
        int index = requestURI.lastIndexOf("/");

        String method = requestURI.substring(index + 1);

        //3.反射
        //3.1 当前Servlet 对象的类型
        Class<? extends Baseconterllor> aClass = this.getClass();
        //3.2 获得 反射的具体方法
        Method declaredMethod = aClass.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
        //3.3 反射调用方法
        declaredMethod.invoke(this, request, response);


    }


    /**
     * 统一响应
     * @param response
     * @param flag   成功标记位
     */
    @SneakyThrows
    protected void writeResult(HttpServletResponse response,  boolean flag) {
        if (flag)
        {
            ResultEntity result = ResultEntity.SUCCESS();

            response.getWriter().write(JSON.toJSONString(result));

        } else {
            ResultEntity result = ResultEntity.ERROR();
            response.getWriter().write(JSON.toJSONString(result));
        }
    }


    @SneakyThrows
    protected void writeResult(HttpServletResponse response,  ResultCode resultCode) {

            ResultEntity result = new ResultEntity(resultCode);

            response.getWriter().write(JSON.toJSONString(result));


    }


    @SneakyThrows
    protected void writeResultAndData(HttpServletResponse response,  Object data) {

        if(data!=null)
        {


            ResultEntity result = new ResultEntity(ResultCode.SUCCESS,data);

            response.getWriter().write(JSON.toJSONString(result));


        }else {

            ResultEntity result = new ResultEntity(ResultCode.NODATA);

            response.getWriter().write(JSON.toJSONString(result));

        }

    }
}
